package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class Sign extends AppCompatActivity {
    Button back;
    Button submit;
    EditText name;
    EditText psw;
    private UserDBHelper dbHelper;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_sign);
        name = findViewById(R.id.sign_name);
        psw = findViewById(R.id.sign_psw);
        back = findViewById(R.id.back);
        submit = findViewById(R.id.submit);
        dbHelper = new UserDBHelper(this);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = name.getText().toString();
                String password = psw.getText().toString();

                if (!username.isEmpty() && !password.isEmpty()) {
                    SQLiteDatabase db = dbHelper.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    values.put(UserDBHelper.COLUMN_NAME, username);
                    values.put(UserDBHelper.COLUMN_PASSWORD, password);

                    long newRowId = db.insert(UserDBHelper.TABLE_NAME, null, values);
                    if (newRowId != -1) {
                        Toast.makeText(Sign.this, "提交成功！", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(Sign.this, "提交失败，请重试！", Toast.LENGTH_SHORT).show();
                    }
                    db.close();
                } else {
                    Toast.makeText(Sign.this, "请输入账号和密码！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                Toast.makeText(Sign.this, name.getText().toString(), Toast.LENGTH_SHORT).show();
                intent.putExtra("name", name.getText().toString());
                intent.putExtra("psw", psw.getText().toString());
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }
}